package com.wolfeyes.common.utils.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

//import org.apache.log4j.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wolfeyes.common.utils.character.ParamUtils;

/**
 * @description 对象序列化与反序列化-Util工具类
 * @projectName film
 * @className SerializeUtilss.java
 * @author yanyljava
 * @email yanyljava@qq.com
 * @date 2016-06-01 15:53:58
 * @since 2017年02月02日下午5:37:39
 * @createTime 2016年06月01日 下午17:04:13
 * @version 1.0.0
 */
public class SerializeUtilss {
	
	/**
	 * slf4j日志对象
	 */
    //private static final Logger logger = Logger.getLogger(SerializeUtilss.class);
	private static final Logger logger = LoggerFactory.getLogger(SerializeUtilss.class);

    /**
     * @description 序列化-serialize-toBytes
     * @param object 待序列化的对象
     * @author yanyl
     * @since 2018年10月08日上午13:37:39
     * @return byte[] 存储对象的字节数组
     * @throws Exception 异常
     */
    public static byte[] toBytes(Object obj) {
        byte[] ret = null;
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(bao);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            ret = bao.toByteArray();
        } catch (Exception e1) {
        	
        	logger.error("序列化为byte数组失败:" + e1.toString());
        }
        return ret;
    }

    /**
     * @description 反序列化-deserialize-getObjectFromBytes
     * @param bytes 存储对象的字节数组
     * @author yanyl
     * @since 2018年10月08日上午13:37:39
     * @return Object 反序列化后获得的对象
     * @throws Exception 异常
     */
    //@SuppressWarnings("unchecked")
	public static <T> T getObjectFromBytes(Class<T> clazz, byte[] data) {
		
        T result = null;
        
        // 判断byte[]数组是否为空；
        if (ParamUtils.isEmpty(data)) {
            return null;
        }
        
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        
        try {
        	
        	// 创建对象输入流objectInputStream
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            
			result = (T) objectInputStream.readObject();
            
            objectInputStream.close();
		} catch (Exception e) {
        	logger.error("反序列化失败:{}" + e.toString());
        }

        return result;
    }
}
